package org.ithink.util;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;

public class XmlUtils {
  
  /**
   * 格式化XML
   * 
   * @param xmlData :
   * @param xslFileName
   */
  public static String formatXmlFromXsl(String xmlData, String xslFileName) {

    String xml = "";
    try {
      StringWriter writer = new StringWriter();
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      byte[] bytes = xmlData.getBytes("utf-8");
      ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
      Document document = builder.parse(new InputSource(bais));
      DOMSource source = new DOMSource(document);

      TransformerFactory tFac = TransformerFactory.newInstance();
      Source xslSource = new StreamSource(xslFileName);
      Transformer t = tFac.newTransformer(xslSource);
      Result result = new StreamResult(writer);
      t.transform(source, result);
      xml = writer.toString();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return xml;
  }

  /**
   * MAP -> XML
   */
  public static String map2Xml(Map hashMap) {

    if (hashMap == null || hashMap.isEmpty()) {
      return "";
    }

    StringBuffer strBuffer = new StringBuffer();
    Iterator it = hashMap.keySet().iterator();

    while (it.hasNext()) {
      String key = (String) it.next();
      Object value = hashMap.get(key);
      strBuffer.append("<" + key + "><![CDATA[" + (value == null ? "" : value) + "]]></" + key + ">\n");
    }

    return strBuffer.toString();
  }
  
  /**
   * ENTITY -> XML
   */
  public static String entity2Xml(Object obj) {
    XStream xstream = new XStream();
    xstream.alias(obj.getClass().getSimpleName(), obj.getClass());
    return xstream.toXML(obj);
  }
  
  /**
   * List<Map> -> xml
   * @param java.util.List<Map>
   */
  public static String getGridXmlMap(List list){
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < list.size(); i++) {
      sb.append("<item>\n");
      Map hashMap = (HashMap) list.get(i);
      sb.append(map2Xml(hashMap));
      sb.append("</item>\n");
    }
    return sb.toString();
    
  }

  public static void main(String[] args) {
    Map map = new HashMap();
    map.put("asdf", 123);
    
    System.out.println(entity2Xml(map));
  }
  
  /*
  prePath = getClass().getResource("").getPath();
  // 1、转换参数为XML
  Map map = new HashMap();
  map.put("nhcode", nhCode);
  map.put("frcode", xt.getUnitefrcode());
  map.put("unitecode", xt.getUnitecode());
  String localXml = HisUtil.getGridStrByMap(map);
  StringBuffer sb = new StringBuffer();
  sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
    .append("<map>")
    .append(localXml)
    .append("</map>");
  
  // 2、通过XSL格式化XML为SOAPXML
  String reqXml = XmlUtil.formatXmlFromXsl(sb.toString(), prePath + "/In200217.xsl");
  
  // 3、发送SOAP包
  SoapUtil soapUtil = new SoapUtil(xt.getAdds(), reqXml);
  String resXml = soapUtil.send();
  
  // 4、通过XSL格式化XML为本地XML
  String localResXml = XmlUtil.formatXmlFromXsl(resXml, prePath + "/Out200217.xsl");
  
  // 5、解析本地XML为本地实体
  XStream xstream = new XStream();
  xstream.alias("person", Person.class);
  xstream.alias("persons", java.util.ArrayList.class);
  List persons = (List)xstream.fromXML(localResXml);
*/
}
